#include "CSurface.h"

CSurface::CSurface()
{
	fileName = NULL;
}

CSurface::CSurface(char* _fileName)
{
	m_pDevice = GL_graphic->GetDevice();
	m_pBackBuffer = GL_graphic->GetBackBuffer();
	fileName = _fileName;
	this->Load();
}

CSurface::~CSurface()
{
	if(this->m_pSurface != NULL){
		this->m_pSurface->Release();
	}
}

CSurface* CSurface::create(char* _fileName)
{
	CSurface* temp = new CSurface(_fileName);
	return temp;
}

D3DXIMAGE_INFO CSurface::getInfo()
{
	return m_Info;
}

void CSurface::Load()
{
	HRESULT result = D3DXGetImageInfoFromFile(fileName, &m_Info);
	if (result != D3D_OK)
	{
		GLMessage("Can not load surface");
		GLLogger("[ERROR] Failed to get image m_Info '%s'", fileName);
		return;
	}

	RECT s = {0,0,m_Info.Width,m_Info.Height};
	m_rSize = s;
		
	m_pDevice->CreateOffscreenPlainSurface(
		m_Info.Width,				// width
		m_Info.Height,			// height
		D3DFMT_X8R8G8B8,		// format
		D3DPOOL_DEFAULT ,		
		&m_pSurface,
		NULL);

	result = D3DXLoadSurfaceFromFile(
		m_pSurface, 		// surface
		NULL,			// destination palette	
		NULL,			// destination rectangle 
		fileName,			
		NULL,			// source rectangle
		D3DX_DEFAULT, 	// filter image
		0,				// transparency (0 = none) //color
		NULL);			// reserved

	if (result != D3D_OK)
	{
		GLMessage("Can not load surface");
		GLLogger("[ERROR] D3DXLoadSurfaceFromFile() failed");
		return;
	}
	else
		GLLogger("[SUCCESS] '%s' has been loaded ", fileName);
	m_pDevice->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&m_pBackBuffer);
}

void CSurface::Draw(const RECT* sRect, const RECT* dRect)
{
	m_pDevice->StretchRect(
		this->m_pSurface,		// from 
		sRect,				// which portion?
		m_pBackBuffer,		// to 
		dRect,				// which portion?
		D3DTEXF_NONE);
}

void CSurface::Draw(int x, int y)
{
	RECT dr = {x, y, m_rSize.right + x, m_rSize.bottom + y};

	m_pDevice->StretchRect(
		this->m_pSurface,		// from 
		&this->m_rSize,//NULL				// which portion?
		m_pBackBuffer,		// to 
		&dr,				// which portion?
		D3DTEXF_NONE);
}